import graph

def initial(graph_db):
    initial_instance_db = graph.InstanceDb()
    instance_count = 0
    for graph_id in graph_db.Graphs.keys():
        for vertex_id in graph_db.Graphs[graph_id].Vertices.keys():
            instance_count += 1
            curr_instance = graph.Instance(instance_count, graph_id)
            curr_instance.add_vertex(vertex_id)
            initial_instance_db.add_instance(curr_instance)
    return initial_instance_db

def expand_instances(instance_db, graph_db):
    curr_instance_db = graph.InstanceDb()
    instance_count = 0
    for instance_id in instance_db.Instances.keys():
        instance = instance_db.Instances[instance_id]
        for vertex_id in instance.Vertices:
            for edge_id in graph_db.Graphs[instance.graph_id].Vertices[vertex_id].incident_edges:
                if edge_id not in instance.Edges:
                    for incident_vertex_id in graph_db.Graphs[instance.graph_id].Edges[edge_id].get_vertices():
                        if incident_vertex_id not in instance.Vertices:
                            instance_count += 1
                            curr_instance = graph.Instance(instance_count, instance.graph_id)
                            curr_instance.add_vertex(incident_vertex_id)
                            curr_instance.add_edge(edge_id)
                            for old_vertex in instance.Vertices:
                                curr_instance.add_vertex(old_vertex)
                            for old_edge in instance.Edges:
                                curr_instance.add_edge(old_edge)
                            curr_instance_db.add_instance(curr_instance)
    return curr_instance_db

def remove_identical_instances(instance_db):
    group_db = {}
    group_count = 0
    for instance_id in instance_db.Instances.keys():
        instance = instance_db.Instances[instance_id]
        if group_count == 0:
            group_count += 1
            group_db[group_count] = instance_id
        else:
            new = True
            for group_id in group_db.keys():
                group_instance = instance_db.Instances[group_db[group_id]]                
                if group_instance.graph_id == instance.graph_id and \
                        group_instance.Vertices == instance.Vertices and \
                        group_instance.Edges == instance.Edges:
                    new = False
                    del instance_db.Instances[instance_id]
                    instance_db.count -= 1
                    break
            if new:
                group_count += 1
                group_db[group_count] = instance_id
                

                
                
